#!/bin/sh
if [ $# != 1 ]; then
    echo $#
    echo "./audio2cfile_array.sh <input dir>"
    exit 0
fi

INPUT_DIR="$1/arrays_wav"
OUPUT_DIR="$1/arrays_adpcm"
OUTPUT_FILE="$PWD/$1/audio_arrays.c"
FILE_MAPPING="\n\nXIP_DATA audio_array_t g_audio_name_array[] = {"
FILE_MAPPING_LEN=0

rm -rf "${OUPUT_DIR}"
mkdir -p "${OUPUT_DIR}"

cd ${INPUT_DIR}
AUDIO_FILE_LIST=`ls *.wav`
cd -

#### convert the wav to adpcm, change the name to audioxx and generate the content-name mapping ####
for i in ${AUDIO_FILE_LIST};do
    echo "adpcm convert $i"
    AUDIO_NAME=`echo $i | awk -F[.] '{printf "%s",$1}'`
    FILE_MAPPING="${FILE_MAPPING}\n {${AUDIO_NAME}_wav,\tsizeof(${AUDIO_NAME}_wav)},"
    FILE_MAPPING_LEN=$((${FILE_MAPPING_LEN}+1))
    ffmpeg -y -hide_banner -loglevel error -i ${INPUT_DIR}/$i -f wav -acodec adpcm_ms ${OUPUT_DIR}/${AUDIO_NAME}.wav
    # ./wav2adpcm -q -y -e ${INPUT_DIR}/$i ${OUPUT_DIR}/${AUDIO_NAME}.wav
done
FILE_MAPPING="${FILE_MAPPING}\n};\n"

#### convert the audio bin to c source file ####
rm -f ${OUTPUT_FILE}
printf "#include \"local_audio.h\"\n\n" > ${OUTPUT_FILE}

cd ${OUPUT_DIR}
ADPCM_FILE_LIST=`ls *.wav`
echo "write to ${OUTPUT_FILE}"


for i in ${ADPCM_FILE_LIST};do
    echo "write $i"
    printf "XIP_DATA " >>  ${OUTPUT_FILE}
    xxd -i $i >> ${OUTPUT_FILE}
    printf "\n" >> ${OUTPUT_FILE}
done
cd -

printf "${FILE_MAPPING}" >> ${OUTPUT_FILE}
printf "XIP_DATA int g_audio_name_array_len = ${FILE_MAPPING_LEN};\n" >> ${OUTPUT_FILE}

INDEX_MAP=`python gen_array_map.py ${INPUT_DIR}`
printf "${INDEX_MAP}\n\n" >> ${OUTPUT_FILE}

#mv "${OUTPUT_FILE}" ..
echo "write to ${OUTPUT_FILE} successfully"

